package com.cjf.androidstudy.component;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.cjf.androidstudy.R;
import com.cjf.androidstudy.utils.FileUtils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class ComponentActivity extends AppCompatActivity {

    private static final String TAG = "ComponentActivity";
    private TextView tvShow;
    private EditText editText;
    private EditText editText2;
    private float fontSize = 50.0f;
    private ImageView imageView;
    private ProgressBar progressBar;
    private ProgressBar progressBar2;
    private ScrollView scrollView;
    private SharedPreferences sharedPreferences;
    private String saveFileName = "ComponentActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_component);
        tvShow = findViewById(R.id.helloworld);
        tvShow.setTextSize(fontSize);//设置初始字体大小
        Button button = findViewById(R.id.button1);

        imageView = findViewById(R.id.image1);
        Button button2 = findViewById(R.id.button2);

        Button button3 = findViewById(R.id.button3);
        progressBar = findViewById(R.id.progressBar1);

        Button button4 = findViewById(R.id.button4);
        progressBar2 = findViewById(R.id.progressBar2);

        Button button5 = findViewById(R.id.button5);

        editText = findViewById(R.id.edittext1);
        Button editButton = findViewById(R.id.text1Button);
        editText2 = findViewById(R.id.edittext2);
        Button editButton2 = findViewById(R.id.text1Button2);

        scrollView = findViewById(R.id.scrollView1);
        // 不想显示右边的下拉条的话，可以设置不显示。
        scrollView.setVerticalScrollBarEnabled(false);

        // 从文件中读取数据，进行初始化
        String editTextContent = null;
        try {
            editTextContent = FileUtils.loadData(this, saveFileName);
        } catch (IOException e) {
            Log.e(TAG, "onCreate: ", e);
        }
        if (editTextContent != null) {
            editText.setText(editTextContent);
        }

        // 从SharedPreferences文件中读取数据（key-value形式）
        sharedPreferences = getSharedPreferences(saveFileName, MODE_PRIVATE);
        int id = sharedPreferences.getInt("id", 1);
        String name = sharedPreferences.getString("name", "");
        boolean married = sharedPreferences.getBoolean("married", false);
        Log.i(TAG, "id= " + id + ";name= " + name + ";married= " + married);
        editText2.setText(name);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示intent，跳转到其他activity
//                Intent intent = new Intent(ComponentActivity.this, LoginActivity.class);

//               implicitIntent 这个字符串是在AndroidManifest定义的，见下文
//                Intent intent = new Intent(Intent.ACTION_VIEW);
                Intent intent = new Intent("implicitIntent");
//                intent.setData(Uri.parse("https://www.baidu.com"));
                intent.setData(Uri.parse("tel2://10086"));
                intent.putExtra("name", "cjf");
                startActivity(intent);
            }
        });

        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Toast.makeText(ComponentActivity.this, "第一个toast", Toast.LENGTH_SHORT).show();
                String editTextContent = editText.getText().toString();
                Toast.makeText(ComponentActivity.this, editTextContent, Toast.LENGTH_SHORT).show();
                try {
                    FileUtils.saveData(v.getContext(), saveFileName, editTextContent);
                } catch (IOException e) {
                    Log.e(TAG, "onClick: ", e);
                }
            }
        });

        editButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 会以xml的形式保存key-value
                String editTextContent2 = editText2.getText().toString();
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putInt("id", 1);
                editor.putString("name", editTextContent2);
                editor.putBoolean("married", false);
                editor.apply();
                Toast.makeText(ComponentActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(ComponentActivity.this).load(R.drawable.image2).into(imageView);
//                imageView.setImageResource(R.drawable.image2);
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(ComponentActivity.this);
                alertDialog.setTitle("我是一个AlertDialog");
                alertDialog.setMessage("切换进度条");
//                alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                }).show();
                alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
                if (progressBar.getVisibility() == View.GONE) {
                    progressBar.setVisibility(View.VISIBLE);
                } else {
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int progress = progressBar2.getProgress();
                progress = progress + 10;
                progressBar2.setProgress(progress);
            }
        });

        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //       startTimer("我的第一个定时器",3000);
                Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
                        .putExtra(AlarmClock.EXTRA_MESSAGE, "ddd")
                        .putExtra(AlarmClock.EXTRA_LENGTH, "22222")
                        .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
                startActivity(intent);
            }
        });

        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        // 判断是在顶部、底部
                        if (scrollView.getScrollY() <= 0) {
                            Toast.makeText(ComponentActivity.this, "到达顶部", Toast.LENGTH_SHORT).show();
                            break;
                        } else if (scrollView.getChildAt(0).getMeasuredHeight() <=
                                scrollView.getHeight() + scrollView.getScrollY()) {
                            Toast.makeText(ComponentActivity.this, "到达底部", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    //    /**
//     * 将内容保存到文件里面
//     * @param editTextContent
//     */
    private void saveEditTextContent(String editTextContent) {
        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileOutputStream = openFileOutput("data", Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(editTextContent);
        } catch (Exception e) {
            Log.e(TAG, "saveData: ", e);
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    Log.e(TAG, "saveData: ", e);
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    Log.e(TAG, "saveData: ", e);
                }
            }
        }
    }

    /**
     * 表示当activity创建选项菜单时回调的方法
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //创建菜单的第一种方式 xml文件
        getMenuInflater().inflate(R.menu.main_menu, menu);

        //创建菜单的代码添加方式
        // add(groupId 菜单项分组,ItemId 菜单项唯一标示id,order 表示菜单项的排序,菜单项展示的文本)
//        menu.add(Menu.NONE, ITEMID, Menu.NONE, "设置字体");
//        MenuItem item = menu.findItem(R.id.action_style);
//        //2.快速绑定菜单某一项的方式
//        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                Toast.makeText(MainActivity.this,item.getTitle().toString(),Toast.LENGTH_SHORT).show();
//                return false;
//            }
//        });
        return true;
    }

    /**
     * 绑定Options Menu的事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemid = item.getItemId();// 获取当前点击菜单的资源ID
        switch (itemid) {
            case R.id.font_add:
                fontSize += 5;
                tvShow.setTextSize(fontSize);//设置字体大小
                break;
            case R.id.font_sub:
                fontSize -= 5;
                tvShow.setTextSize(fontSize);//设置字体大小
                break;
            case R.id.action_color:
                //随机生成颜色
                int red = (int) (Math.random() * 256);
                int green = (int) (Math.random() * 256);
                int blue = (int) (Math.random() * 256);
                tvShow.setTextColor(Color.rgb(red, green, blue));
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 倒计时时钟
     *
     * @param message 附加信息
     * @param seconds 多少秒
     */
    public void startTimer(String message, int seconds) {
        Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
                .putExtra(AlarmClock.EXTRA_MESSAGE, message)
                .putExtra(AlarmClock.EXTRA_LENGTH, seconds)
                .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }

}
